package com.bloom.spider.controller;

import java.util.List;

import com.bloom.common.utils.StringUtils;
import com.bloom.spider.service.ISpiderConfigService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bloom.common.annotation.Log;
import com.bloom.common.core.controller.BaseController;
import com.bloom.common.core.domain.AjaxResult;
import com.bloom.common.enums.BusinessType;
import com.bloom.spider.domain.SpiderMission;
import com.bloom.spider.service.ISpiderMissionService;
import com.bloom.common.utils.poi.ExcelUtil;
import com.bloom.common.core.page.TableDataInfo;

/**
 * 爬虫任务Controller
 * 
 * @author bloom
 * @date 2021-04-28
 */
@RestController
@RequestMapping("/spider/spiderMission")
public class SpiderMissionController extends BaseController
{
    @Autowired
    private ISpiderMissionService spiderMissionService;

    @Autowired
    private ISpiderConfigService spiderConfigService;

    /**
     * 查询爬虫任务列表
     */
    @PreAuthorize("@ss.hasPermi('spider:spiderMission:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpiderMission spiderMission)
    {
        startPage();
        List<SpiderMission> list = spiderMissionService.selectSpiderMissionList(spiderMission);
        return getDataTable(list);
    }

    /**
     * 导出爬虫任务列表
     */
    @PreAuthorize("@ss.hasPermi('spider:spiderMission:export')")
    @Log(title = "爬虫任务", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SpiderMission spiderMission)
    {
        List<SpiderMission> list = spiderMissionService.selectSpiderMissionList(spiderMission);
        ExcelUtil<SpiderMission> util = new ExcelUtil<SpiderMission>(SpiderMission.class);
        return util.exportExcel(list, "爬虫任务数据");
    }

    /**
     * 获取爬虫任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('spider:spiderMission:query')")
    @GetMapping(value = "/{missionId}")
    public AjaxResult getInfo(@PathVariable("missionId") Long missionId)
    {
        return AjaxResult.success(spiderMissionService.selectSpiderMissionById(missionId));
    }

    /**
     * 新增爬虫任务
     */
    @PreAuthorize("@ss.hasPermi('spider:spiderMission:add')")
    @Log(title = "爬虫任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpiderMission spiderMission)
    {
        String entryUrls=spiderMission.getEntryUrls();
        if (StringUtils.isEmpty(entryUrls)) {
            return AjaxResult.error("入口URL必填!多条用逗号分隔或者换行分隔!");
        }
        String[] arr=null;
        if(entryUrls.contains(",")){
            //前台多条传过来用逗号分隔
            arr=entryUrls.split(",");

        }else{
            //前台多条传过来用换行分隔
            arr=entryUrls.split("\r\n");
        }
        if(arr==null||arr.length==0){
            return AjaxResult.error("入口URL必填!多条用逗号分隔或者换行分隔!");
        }
        boolean isUrlFlag=true;
        String tempUrl="";
        String urlAll="";
        for(String url:arr){
            if(!isURL(url)){
                isUrlFlag=false;
                tempUrl=url;
                break;
            }else{
                urlAll+=url+",";
            }
        }
        if(!isUrlFlag){
            return AjaxResult.error("["+tempUrl+"]不是一个有效的url!");
        }
        if(isUrlFlag){
            if(urlAll.endsWith(",")){
                urlAll=urlAll.substring(0,urlAll.length()-1);
                spiderMission.setEntryUrls(urlAll);
            }
        }
        return toAjax(spiderMissionService.insertSpiderMission(spiderMission));
    }

    private static boolean isURL(String str){
        str = str.toLowerCase();
        String regex = "(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
        return str.matches(regex);
    }


    /**
     * 修改爬虫任务
     */
    @PreAuthorize("@ss.hasPermi('spider:spiderMission:edit')")
    @Log(title = "爬虫任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpiderMission spiderMission)
    {
        String entryUrls=spiderMission.getEntryUrls();
        String[] arr=null;
        if(entryUrls.contains(",")){
            //前台多条传过来用逗号分隔
            arr=entryUrls.split(",");

        }else{
            //前台多条传过来用换行分隔
            arr=entryUrls.split("\r\n");
        }
        if(arr==null||arr.length==0){
            return AjaxResult.error("入口URL必填!多条用逗号分隔或者换行分隔!");
        }
        boolean isUrlFlag=true;
        String tempUrl="";
        String urlAll="";
        for(String url:arr){
            if(!isURL(url)){
                isUrlFlag=false;
                tempUrl=url;
                break;
            }else{
                urlAll+=url+",";
            }
        }
        if(!isUrlFlag){
            return AjaxResult.error("["+tempUrl+"]不是一个有效的url!");
        }
        if(isUrlFlag){
            if(urlAll.endsWith(",")){
                urlAll=urlAll.substring(0,urlAll.length()-1);
                spiderMission.setEntryUrls(urlAll);
            }
        }
        return toAjax(spiderMissionService.updateSpiderMission(spiderMission));
    }

    /**
     * 删除爬虫任务
     */
    @PreAuthorize("@ss.hasPermi('spider:spiderMission:remove')")
    @Log(title = "爬虫任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{missionIds}")
    public AjaxResult remove(@PathVariable Long[] missionIds)
    {
        return toAjax(spiderMissionService.deleteSpiderMissionByIds(missionIds));
    }

    /**
     * 启动爬虫任务
     */
    @PostMapping( "/runSpiderMission/{missionId}")
    @ResponseBody
    public AjaxResult runSpiderMission(@PathVariable("missionId") String missionId)
    {
        return spiderMissionService.runSpiderMission(missionId);
    }
}
